<template>
  <div class="upload-file">
    <el-upload
      drag
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :headers="headers"
      name="file"
      class="upload-file-uploader"
      ref="upload"
    >
      <!-- 上传按钮 -->
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize">
          大小不超过
          <b style="color: #f56c6c">{{ fileSize }}MB</b>
        </template>
        <template v-if="fileType">
          格式为
          <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
        </template>
        的文件
      </div>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { addChapterRes } from "@/api/course/chapter";
export default {
  name: "FileUpload",
  props: {
    // 绑定章节信息
    chapterId: {
      type: String,
      default: "0"
    },
    // 双向绑定值
    value: [String, Object, Array],
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf"]
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      number: 0,
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/course/res/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      videoUrl: ""
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          this.imageUrl = val;
          return val;
        } else {
          this.imageUrl = "";
          return "";
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    }
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$modal.msgError(
            `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
          );
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...（请勿刷新）");
      this.number++;
      return true;
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.videoUrl = res.data.videoUrl;
        if (this.chapterId != 0) {
          // 将视频绑定到该章节
          let chapterRes = {
            chapterId: this.chapterId,
            resId: res.data.resId
          };
          this.bindChapterRess([chapterRes]);
        } else {
          this.$modal.msgSuccess("上传成功");
          this.$modal.closeLoading();
        }
        // 通知父组件
        this.$emit("uploadFinish")
      } else {
        this.$modal.msgError(res.msg);
        this.$modal.closeLoading();
      }
    },
    // 章节绑定附件
    bindChapterRess(chapterRes) {
      addChapterRes(chapterRes)
        .then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess("上传成功,绑定章节成功");
          } else {
            this.$modal.msgError("上传成功,绑定章节失败");
          }
        })
        .finally(() => {
          this.$modal.closeLoading();
        });
    }
  }
};
</script>
